from rest_framework.viewsets import ModelViewSet
from system_config.serializers import CredentialSerializer, NotifySerializer,BlacklistSerializer
from system_config.models import Credential, Notify,BlacklistIP
from rest_framework.response import Response
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.views import APIView

class CredentialViewSet(ModelViewSet):

    queryset = Credential.objects.all()
    serializer_class = CredentialSerializer

    filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend]  # 指定过滤器
    search_fields = ('name', )  # 指定可搜索的字段
    # filter_fields = ('name',)   # 指定过滤的字段

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        res = {'code': 200, 'msg': '创建成功'}
        return Response(res)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        res = {'code': 200, 'msg': '更新成功'}
        return Response(res)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        try:
            self.perform_destroy(instance)
            res = {'code': 200, 'msg': '删除成功'}
            return Response(res)
        except Exception as e:
            res = {'code': 500, 'msg': '该凭据关联其他主机，请先删除关联的主机再操作！'}
            return Response(res)


class NotifyViewSet(ModelViewSet):
    queryset = Notify.objects.all()
    serializer_class = NotifySerializer

    filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend]
    search_fields = ('name',)
    filterset_fields = ('notify_mode',)  # 指定过滤的字段

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        res = {'code': 200, 'msg': '创建成功'}
        return Response(res)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        res = {'code': 200, 'msg': '更新成功'}
        return Response(res)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        try:
            self.perform_destroy(instance)
            res = {'code': 200, 'msg': '删除成功'}
            return Response(res)
        except Exception as e:
            res = {'code': 500, 'msg': '该消息通知关联其他发布配置，请先删除关联的发布配置再操作！'}
            return Response(res)

#判断是否是列表类型
def is_list_type(data):
    return isinstance(data, list)

class BlacklistView(APIView):
    def get(self, request):
        ip = request.META.get('REMOTE_ADDR')
        ip_list_obj = BlacklistIP.objects.all()
        ip_list = []
        for i in ip_list_obj:
            if ',' in i.ip_address:
                ip_list.extend(i.ip_address.split(','))
            else:
                ip_list.append(i.ip_address)
        ip_list = list(set(ip_list))  #列表去重
        res = {'code': 200, 'ip_list': ip_list, 'ip': ip, 'msg': '获取成功'}
        return Response(res)

    def post(self,request):
        ip_address = request.data.get('ip_address')
        if len(ip_address) == 0:   #判断字符串是否等于0，如果等于设置为空字符串
            ip_address = ''
        elif is_list_type(ip_address): # 判断是否是空列表，然后取第一个空字符串
            ip_address = ip_address[0]
        else:
            ip_address = ip_address   #否则正常读取
        #如果有数据则更新，只匹配第一行
        if  BlacklistIP.objects.exists():
            BlacklistIP.objects.update(ip_address=ip_address)
        else:
            BlacklistIP.objects.create(ip_address=ip_address)
        res = {'code': 200, 'msg': '保存成功'}
        return Response(res)
